<template>
    <div class="page-container">
        <!-- Filter Section (Search Card) -->
        <div class="search-card">
            <div class="card-header">
                <span class="card-title">查询条件</span>
            </div>
            <div class="search-section">
                <el-form :model="filters" class="query-form" label-position="top">
                    <el-row :gutter="24">
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="单位名称">
                                <el-input
                                    v-model="filters.unitName"
                                    placeholder="模糊匹配"
                                    clearable
                                    class="custom-input"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="登录账号">
                                <el-input
                                    v-model="filters.username"
                                    placeholder="模糊匹配"
                                    clearable
                                    class="custom-input"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="用户类型">
                                <el-select
                                    v-model="filters.userType"
                                    placeholder="全部"
                                    clearable
                                    class="custom-select"
                                >
                                    <el-option label="企业账号" :value="1" />
                                    <el-option label="市账号" :value="2" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="数据状态">
                                <el-select
                                    v-model="filters.dataStatus"
                                    placeholder="全部"
                                    clearable
                                    class="custom-select"
                                >
                                    <el-option label="正常" :value="0" />
                                    <el-option label="停用" :value="1" />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="地区（市/县）">
                                <el-cascader
                                    v-model="regionSelection"
                                    :options="regionOptions"
                                    :props="regionProps"
                                    clearable
                                    filterable
                                    class="custom-select"
                                    style="width: 100%"
                                    placeholder="请选择市或县"
                                    @change="onRegionChange"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="单位性质">
                                <el-select
                                    v-model="filters.unitNature"
                                    placeholder="选择一级性质"
                                    clearable
                                    filterable
                                    class="custom-select"
                                >
                                    <el-option
                                        v-for="item in natureOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="所属行业">
                                <el-select
                                    v-model="filters.industry"
                                    placeholder="选择一级行业"
                                    clearable
                                    filterable
                                    class="custom-select"
                                >
                                    <el-option
                                        v-for="item in industryOptions"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="统计月份">
                                <el-date-picker
                                    v-model="statMonth"
                                    type="month"
                                    placeholder="选择月份"
                                    value-format="YYYY-MM"
                                    format="YYYY-MM"
                                    class="custom-input"
                                    style="width: 100%"
                                    @change="onMonthChange"
                                />
                            </el-form-item>
                        </el-col>

                        <el-col :xs="24" :sm="12" :md="12" :lg="8">
                            <el-form-item label="日期范围">
                                <el-date-picker
                                    v-model="dateRange"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="起始日期"
                                    end-placeholder="结束日期"
                                    value-format="YYYY-MM-DD"
                                    format="YYYY-MM-DD"
                                    class="custom-input"
                                    style="width: 100%"
                                    @change="onDateRangeChange"
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="12" :lg="8">
                            <el-form-item label="统计季度">
                                <div class="quarter-wrapper">
                                    <el-date-picker
                                        v-model="quarterYear"
                                        type="year"
                                        placeholder="年份"
                                        value-format="YYYY"
                                        format="YYYY"
                                        class="custom-input"
                                        style="flex: 1"
                                        @change="onQuarterChange"
                                    />
                                    <el-select
                                        v-model="quarterValue"
                                        placeholder="季度"
                                        clearable
                                        class="custom-select"
                                        style="width: 120px"
                                        @change="onQuarterChange"
                                    >
                                        <el-option label="Q1" value="Q1" />
                                        <el-option label="Q2" value="Q2" />
                                        <el-option label="Q3" value="Q3" />
                                        <el-option label="Q4" value="Q4" />
                                    </el-select>
                                </div>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <div class="form-actions">
                        <el-button @click="resetFilters" class="btn-secondary" round size="large"
                            >重置</el-button
                        >
                        <el-button
                            type="success"
                            size="large"
                            round
                            :loading="exportLoading"
                            @click="handleExport"
                            class="btn-success-theme"
                        >
                            <el-icon class="mr-1">
                                <Download />
                            </el-icon>
                            导出结果
                        </el-button>
                        <el-button
                            type="primary"
                            @click="fetchList"
                            :loading="loading"
                            class="btn-primary-theme"
                            round
                            size="large"
                        >
                            <el-icon class="mr-1">
                                <Search />
                            </el-icon>
                            查询
                        </el-button>
                    </div>
                </el-form>
            </div>
        </div>

        <!-- Table Section (Table Card) -->
        <div class="table-card">
            <div class="card-header">
                <span class="card-title">查询结果</span>
                <span class="section-subtitle"
                    >共找到 <span class="highlight-num">{{ total }}</span> 条记录</span
                >
            </div>

            <el-table
                :data="tableData"
                v-loading="loading"
                style="width: 100%"
                class="modern-table"
                :header-cell-style="{
                    background: '#f8fafc',
                    color: '#475569',
                    fontWeight: '700',
                    fontSize: '13px',
                    height: '56px',
                    textAlign: 'center',
                }"
                :cell-style="{ textAlign: 'center', padding: '12px 0' }"
            >
                <el-table-column prop="username" label="登录账号" min-width="160" align="center">
                    <template #default="{ row }">
                        <span class="cell-text">{{ row.username }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="单位名称"
                    min-width="180"
                    show-overflow-tooltip
                    align="center"
                >
                    <template #default="{ row }">
                        <span class="cell-primary-text">{{ row.name }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="type" label="用户类型" width="120" align="center">
                    <template #default="scope">
                        <div
                            class="status-badge"
                            :class="scope.row.type === 2 ? 'status-primary' : 'status-success'"
                        >
                            <span class="status-dot"></span>
                            {{ scope.row.type === 2 ? '市账号' : '企业账号' }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="region" label="地区" min-width="220" align="center">
                    <template #default="scope">
                        {{ formatRegionPair(scope.row.cityCode, scope.row.region) }}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="industry"
                    label="行业"
                    width="160"
                    show-overflow-tooltip
                    align="center"
                >
                    <template #default="scope">
                        {{ formatIndustry(scope.row.industry) }}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="nature"
                    label="性质"
                    width="140"
                    show-overflow-tooltip
                    align="center"
                >
                    <template #default="scope">
                        {{ formatNature(scope.row.nature) }}
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100" align="center">
                    <template #default="scope">
                        <div
                            class="status-badge"
                            :class="scope.row.status === 0 ? 'status-success' : 'status-danger'"
                        >
                            <span class="status-dot"></span>
                            {{ scope.row.status === 0 ? '正常' : '停用' }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="createdAt" label="创建时间" width="180" align="center">
                    <template #default="{ row }">
                        <span class="timestamp-text">{{ row.createdAt }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="lastLoginTime" label="最后登录" width="180" align="center">
                    <template #default="{ row }">
                        <span class="timestamp-text">{{ row.lastLoginTime || '-' }}</span>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-wrapper">
                <el-pagination
                    v-model:current-page="pagination.pageNo"
                    v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @current-change="onPageChange"
                    @size-change="onSizeChange"
                />
            </div>
        </div>
    </div>
</template>

<script setup>
import { computed, reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Search, Download } from '@element-plus/icons-vue';
import accountApi from '../../api/account.js';
import natureDict from '../../dict/enterprise_type.json';
import industryDict from '../../dict/enterprise_industry.json';
import {
    getCascaderOptions,
    getNameByCode,
    getCities,
    getCountiesByCity,
    getRegionByCode,
} from '@/utils/regionUtils';

const loading = ref(false);
const exportLoading = ref(false);
const tableData = ref([]);
const total = ref(0);

const filters = reactive({
    unitName: '',
    username: '',
    userType: null,
    cityCode: null,
    countyCode: null,
    regionCode: null,
    dataStatus: null,
    unitNature: null,
    industry: null,
    startDate: '',
    endDate: '',
    statMonth: '',
    statQuarter: '',
});

const pagination = reactive({
    pageNo: 1,
    pageSize: 10,
});

const dateRange = ref([]);
const statMonth = ref('');
const quarterYear = ref('');
const quarterValue = ref('');

const regionSelection = ref([]);
const regionOptions = computed(() =>
    getCities().map((city) => ({
        label: city.name,
        value: city.code,
        children: getCountiesByCity(city.code).map((county) => ({
            label: county.name,
            value: county.code,
        })),
    }))
);

const regionProps = {
    multiple: false,
    checkStrictly: true,
    emitPath: true,
};

const natureOptions = computed(() =>
    natureDict
        .filter((item) => item.parentId === 0)
        .map((item) => ({ label: item.name, value: item.code }))
);
const industryOptions = computed(() =>
    industryDict
        .filter((item) => item.parentId === 0)
        .map((item) => ({ label: item.name, value: item.code }))
);

const onRegionChange = (val) => {
    const path = Array.isArray(val) ? val : [];
    filters.cityCode = path[0] || null;
    filters.countyCode = path[1] || null;
    filters.regionCode = path.length ? path[path.length - 1] : null;
};

const onDateRangeChange = (val) => {
    filters.startDate = val && val.length ? val[0] : '';
    filters.endDate = val && val.length ? val[1] : '';
    if (val && val.length) {
        statMonth.value = '';
        quarterYear.value = '';
        quarterValue.value = '';
        filters.statMonth = '';
        filters.statQuarter = '';
    }
};

const onMonthChange = (val) => {
    filters.statMonth = val || '';
    if (val) {
        dateRange.value = [];
        filters.startDate = '';
        filters.endDate = '';
        quarterYear.value = '';
        quarterValue.value = '';
        filters.statQuarter = '';
    }
};

const onQuarterChange = () => {
    if (quarterYear.value && quarterValue.value) {
        filters.statQuarter = `${quarterYear.value}-${quarterValue.value}`;
        filters.statMonth = '';
        statMonth.value = '';
        dateRange.value = [];
        filters.startDate = '';
        filters.endDate = '';
    } else {
        filters.statQuarter = '';
    }
};

const buildPayload = () => {
    return {
        unitNameFuzzy: filters.unitName || undefined,
        usernameFuzzy: filters.username || undefined,
        userType: filters.userType || undefined,
        cityCode: filters.cityCode || undefined,
        countyCode: filters.countyCode || undefined,
        dataStatus: filters.dataStatus !== null ? filters.dataStatus : undefined,
        unitNature: filters.unitNature || undefined,
        industry: filters.industry || undefined,
        regionCode: filters.regionCode || undefined,
        startDate: filters.startDate || undefined,
        endDate: filters.endDate || undefined,
        statMonth: filters.statMonth || undefined,
        statQuarter: filters.statQuarter || undefined,
        pageNo: pagination.pageNo,
        pageSize: pagination.pageSize,
        orderBy: 'created_at desc',
    };
};

const findNameByCodeTopLevel = (list, code) => {
    if (!code || !Array.isArray(list)) return '';
    for (const item of list) {
        if (item.code === code) return item.name;
        if (item.children && item.children.some((c) => c.code === code)) {
            return item.name;
        }
    }
    return '';
};

const formatRegion = (code) => (code ? getNameByCode(code) : '');
const formatIndustry = (code) => findNameByCodeTopLevel(industryDict, code);
const formatNature = (code) => findNameByCodeTopLevel(natureDict, code);
const formatRegionPair = (cityCode, regionCode) => {
    const names = [];
    let current = regionCode ? getRegionByCode(regionCode) : null;

    if (!current && cityCode) {
        const cityNode = getRegionByCode(cityCode);
        if (cityNode) {
            names.unshift(cityNode.name);
        }
        return names.join(' / ');
    }

    while (current) {
        if (current.name) {
            names.unshift(current.name);
        }
        if (current.parentId == null || current.parentId == 0) {
            break;
        }
        const parent = getRegionByCode(current.parentId);
        if (!parent) {
            break;
        }
        current = parent;
    }

    return names.join(' / ');
};

const fetchList = async () => {
    loading.value = true;
    try {
        const payload = buildPayload();
        const res = await accountApi.searchAccounts(payload);
        if (res.code === 200) {
            tableData.value = res.data?.list || [];
            total.value = res.data?.totalCount || 0;
        } else {
            ElMessage.error(res.info || '查询失败');
        }
    } catch (e) {
        ElMessage.error(e?.message || '查询失败');
    } finally {
        loading.value = false;
    }
};

const onPageChange = (page) => {
    pagination.pageNo = page;
    fetchList();
};

const onSizeChange = (size) => {
    pagination.pageSize = size;
    pagination.pageNo = 1;
    fetchList();
};

const resetFilters = () => {
    filters.unitName = '';
    filters.username = '';
    filters.userType = null;
    filters.cityCode = null;
    filters.countyCode = null;
    filters.regionCode = null;
    filters.dataStatus = null;
    filters.unitNature = null;
    filters.industry = null;
    filters.startDate = '';
    filters.endDate = '';
    filters.statMonth = '';
    filters.statQuarter = '';
    dateRange.value = [];
    statMonth.value = '';
    quarterYear.value = '';
    quarterValue.value = '';
    regionSelection.value = [];
    pagination.pageNo = 1;
    fetchList();
};

const handleExport = async () => {
    exportLoading.value = true;
    try {
        const payload = { ...buildPayload(), pageNo: 1, pageSize: 50000 };
        const res = await accountApi.exportAccounts(payload);
        const blob = res.data instanceof Blob ? res.data : res;
        const disposition = res.headers ? res.headers['content-disposition'] : '';
        let filename = 'account_export.csv';
        if (disposition) {
            const match = disposition.match(/filename\*=UTF-8''(.+)/);
            if (match && match[1]) {
                filename = decodeURIComponent(match[1]);
            }
        }
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = filename;
        link.click();
        window.URL.revokeObjectURL(url);
        ElMessage.success('导出成功');
    } catch (e) {
        ElMessage.error(e?.message || '导出失败');
    } finally {
        exportLoading.value = false;
    }
};

onMounted(() => {
    fetchList();
});
</script>

<style scoped lang="scss">
/* --- Global Resets & Layout --- */
.page-container {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    padding: 24px 40px;
    box-sizing: border-box;
    // background-color: #f8fafc;
    color: #1e293b;
    font-family:
        'Inter',
        -apple-system,
        BlinkMacSystemFont,
        'Segoe UI',
        Roboto,
        sans-serif;
}

/* Header */
.header-left {
    display: flex;
    align-items: center;
    gap: 24px;
}

.page-title {
    font-size: 28px;
    font-weight: 800;
    margin: 0 0 8px 0;
    letter-spacing: -0.02em;
    color: white;
}

.page-description {
    font-size: 15px;
    opacity: 0.9;
    margin: 0;
    font-weight: 400;
    color: white;
}

/* Search Card */
.search-card {
    background: #ffffff;
    border-radius: 16px;
    box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.02);
    margin-bottom: 24px;
    border: 1px solid rgba(241, 245, 249, 1);
    overflow: hidden;
}

.card-header {
    padding: 16px 24px;
    border-bottom: 1px solid #f1f5f9;
    background: #fafafa;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-title {
    font-size: 15px;
    font-weight: 700;
    color: #0f172a;
}

.search-section {
    padding: 24px;
}

.query-form {
    margin-bottom: 0;

    :deep(.el-form-item) {
        margin-bottom: 20px;

        .el-form-item__label {
            font-weight: 600;
            color: #475569;
            padding-bottom: 4px;
        }
    }

    .quarter-wrapper {
        display: flex;
        gap: 8px;
        align-items: center;
    }
}

.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 12px;
    padding-top: 24px;
    border-top: 1px dashed #e2e8f0;
}

/* Table Card */
.table-card {
    background: #ffffff;
    border-radius: 24px;
    box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.03);
    border: 1px solid rgba(241, 245, 249, 1);
    overflow: hidden;
    margin-bottom: 24px;
}

.section-subtitle {
    font-size: 13px;
    color: #64748b;

    .highlight-num {
        color: #4f46e5;
        font-weight: 700;
        font-size: 15px;
        padding: 0 2px;
    }
}

/* Modern Table Styles */
.modern-table {
    border-radius: 16px;
    --el-table-border-color: #f1f5f9;
    --el-table-row-hover-bg-color: #f8fafc;
    --el-table-header-bg-color: #f8fafc;
}

.cell-primary-text {
    font-size: 14px;
    font-weight: 600;
    color: #0f172a;
}

.cell-text {
    font-size: 13px;
    color: #64748b;
}

.timestamp-text {
    font-variant-numeric: tabular-nums;
    color: #334155;
    font-size: 13px;
    font-weight: 500;
}

/* Status Badges */
.status-badge {
    display: inline-flex;
    align-items: center;
    padding: 4px 12px;
    border-radius: 99px;
    font-size: 12px;
    font-weight: 600;
    line-height: 1.5;
}

.status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 8px;
}

.status-success {
    background: #ecfdf5;
    color: #059669;
    .status-dot {
        background: #10b981;
    }
}
.status-primary {
    background: #eff6ff;
    color: #2563eb;
    .status-dot {
        background: #3b82f6;
    }
}
.status-warning {
    background: #fff7ed;
    color: #ea580c;
    .status-dot {
        background: #f97316;
    }
}
.status-danger {
    background: #fef2f2;
    color: #dc2626;
    .status-dot {
        background: #ef4444;
    }
}

/* Buttons */
.btn-primary-theme {
    background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%) !important;
    border: none !important;
    color: white !important;
    font-weight: 600;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(79, 70, 229, 0.25);
    transition: all 0.2s ease;
    padding: 10px 24px;
}

.btn-primary-theme:hover {
    background: linear-gradient(135deg, #4338ca 0%, #4f46e5 100%) !important;
    transform: translateY(-1px);
    box-shadow: 0 8px 20px rgba(79, 70, 229, 0.35);
}

.btn-success-theme {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
    border: none !important;
    color: white !important;
    font-weight: 600;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.25);
    transition: all 0.2s ease;
    padding: 10px 24px;
}

.btn-success-theme:hover {
    background: linear-gradient(135deg, #059669 0%, #047857 100%) !important;
    transform: translateY(-1px);
    box-shadow: 0 8px 20px rgba(16, 185, 129, 0.35);
}

.btn-secondary {
    background: #fff;
    border: 1px solid #e2e8f0;
    color: #475569;
    font-weight: 500;
    border-radius: 8px;
    padding: 10px 24px;
}

.btn-secondary:hover {
    background: #f8fafc;
    color: #1e293b;
    border-color: #cbd5e1;
}

/* Inputs */
.custom-input,
.custom-select {
    :deep(.el-input__wrapper) {
        border-radius: 8px;
        box-shadow: 0 0 0 1px #e2e8f0 inset;
        padding: 6px 12px;
        &.is-focus {
            box-shadow: 0 0 0 2px #818cf8 inset;
        }
    }
}

.pagination-wrapper {
    padding: 16px 24px;
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #f1f5f9;
}

.mr-1 {
    margin-right: 4px;
}
</style>
